package geektime.concurrent.part2.race;

import java.util.*;

/**
 * 多线程生成随机数的工作类
 */
public class MultiThreadGenWorker implements GenRunnable {
    // 需要操作的段位
    private int offset;

    // 需要操作的数据量
    private int size;

    // 需要操作的共享数据
    private MultiThreadShareData shareData;

    public MultiThreadGenWorker(int offset, int size, MultiThreadShareData shareData) {
        this.offset = offset;
        this.size = size;
        this.shareData = shareData;
    }

    @Override
    public void run() {
        genRandomNumber();
    }

    @Override
    public void genRandomNumber() {
        Random random = new Random(System.currentTimeMillis());
        for (int i = 0; i < size; i++) {
            // scoreList是ArrayList容器，需要时使用synchronized保证线程安全
            synchronized (MultiThreadGenWorker.class) {
                shareData.getScoreList().add(new Integer(random.nextInt(shareData.COUNT)));
            }
        }
        // 生成随机数的动作完成后，让倒计时门栓countDown
        shareData.getGenRandomLatch().countDown();
    }

}
